﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace A2PongGame
{
    public class Ball : DrawableGameComponent
    {
        public Texture2D texture { get; set; }
        public Rectangle rectSource { get; set; }

        public int speedX { get; set; }
        public int speedY { get; set; }

        public void setXY(int x, int y) { rectSource = new Rectangle(x + speedX, y + speedY, rectSource.Width, rectSource.Height); }

        public Ball(Game game)
            : base(game)
        {
            sp = Game1.spriteBatch;
            speedX = -3;
            speedY = 1;

            reset = new Rectangle(Game1.screenWidth / 2, Game1.screenHeight / 2, 8, 8);

            rectSource = reset;

            texture = new Texture2D(game.GraphicsDevice, 1, 1);
            texture.SetData(new Color[] { Color.White });

        }
        public override void Draw(GameTime gameTime)
        {
            //sp.End();
            sp.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);
            sp.Draw(texture, rectSource, Color.White);
            sp.End();
            base.Draw(gameTime);
        }
        public override void Update(GameTime gameTime)
        {
            rectSource = new Rectangle(rectSource.X + speedX, rectSource.Y + speedY, rectSource.Width, rectSource.Height);
            base.Update(gameTime);
            CheckWallCollision();
            CheckWinCondition();
        }

        private void CheckWinCondition()
        {
            if (0 > rectSource.X || rectSource.X > Game1.screenWidth)
            {
               
                if(0 > rectSource.X)
                {
                    Game1.RightPoints++;
                }
                if (rectSource.X > Game1.screenWidth)
                {
                    Game1.LeftPoints++;
                }
                rectSource = reset;
                speedX *= -1;
            }
        }

        private void CheckWallCollision()
        {
            if ( 0 > rectSource.Y  || rectSource.Y > Game1.screenHeight)
            {
                speedY *= -1;
            }
        }


        public SpriteBatch sp { get; set; }

        public Rectangle reset { get; set; }
    }
}
